package com.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class dbCRUD {
    private static Connection connection = null;
    private static PreparedStatement preparedStatement = null;
    private static ResultSet resultSet = null;

    static{
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/order_system";
            String name="root";
            String password = "gzx123zyl920";
            connection = DriverManager.getConnection(url, name, password);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //查询
    public static ResultSet printAll(String sql,Object[] objects){
        //先导入
        try{
            preparedStatement = connection.prepareStatement(sql);
            if (objects[0] != null){
                for (int i = 0; i < objects.length; i++) {
                    preparedStatement.setObject(i+1,objects[i]);
                }
            }
            resultSet = preparedStatement.executeQuery();
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultSet;
    }

    //增删改
    public static int update(String sql,Object[] objects){
        int num = 0;
        try{
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < objects.length; i++) {
                preparedStatement.setObject(i+1,objects[i]);
            }
            num = preparedStatement.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
    }

    //关闭流
    public static void closeAll() {
        try {
            // 关闭ResultSet（如果存在）
            if (resultSet != null) {
                resultSet.close();
                resultSet = null; // 将引用设置为null，以便垃圾回收
            }

            // 关闭PreparedStatement（如果存在）
            if (preparedStatement != null) {
                preparedStatement.close();
                preparedStatement = null; // 将引用设置为null，以便垃圾回收
            }

            // 关闭Connection（如果存在）
            if (connection != null) {
                connection.close();
                connection = null; // 将引用设置为null，以便垃圾回收
            }
        } catch (Exception e) {
            e.printStackTrace(); // 捕获并打印任何可能发生的SQLException
        }
    }
}